import {defineStore} from "pinia";
import {message} from "ant-design-vue";
const initMember = () => {
    fetch('all.txt')
        .then((response) => response.text())
        .then((text) => {
            useStore().group[0].members =text.split('\n')
        })
        .catch((error) => {
            console.error('读取文件时出错：', error);
        });

    fetch('0-3year.txt')
        .then((response) => response.text())
        .then((text) => {
            useStore().group[1].members =text.split('\n')
        })
        .catch((error) => {
            console.error('读取文件时出错：', error);
        });

    fetch('3-10year.txt')
        .then((response) => response.text())
        .then((text) => {
            useStore().group[2].members =text.split('\n')
        })
        .catch((error) => {
            console.error('读取文件时出错：', error);
        });

    fetch('10year.txt')
        .then((response) => response.text())
        .then((text) => {
            useStore().group[3].members =text.split('\n')
        })
        .catch((error) => {
            console.error('读取文件时出错：', error);
        });
}



export const useStore = defineStore('main', {
    state() {
        return {
            participants: [],
            nowGroup: '全体成员',
            group: [
                {
                    groupName: '全体成员',
                    members: [],
                    exclude: []
                },
                {
                    groupName: '3年以下员工',
                    members: [],
                    exclude: []
                },
                {
                    groupName: '3-10年员工',
                    members: [],
                    exclude: []
                },
                {
                    groupName: '10年以上员工',
                    members: [],
                    exclude: []
                }
            ],
            prize: ['名额', '九阳电饭煲', '美的空气炸锅', '飞利浦耳机', '荣耀手表GS4'],
            nowPrize: '',
            results: []
        }
    },
    actions: {
        setNowGroup: function (groupName) {
            this.nowGroup = groupName
        },
        setNowPrize: function (prize) {
            this.nowPrize = prize
        },
        confirmPrize: function (winner) {
            const find = this.group.find(v => v.groupName === this.nowGroup);
            // 避免重复放入
            if(find.exclude.includes(winner)) {
                return
            }

            if (find) {
                find.exclude.push(winner)
                find.members = find.members.filter(v => v !== winner)
                this.results.push({
                    prize: this.nowPrize,
                    winner: winner
                })
                message.success('恭喜' + winner + '获得' + this.nowPrize)
            }
        },
        init() {
            initMember()
            this.group.forEach(v => {
                v.exclude = []
            })
            this.results = []
        }
    },
    persist: true
})
